class ChatComponent {
    constructor(container, options) {
        this.container = container;
        this.options = Object.assign({}, defaults, options);
        this.isChatVisible = false; // 聊天窗口初始状态为不可见
        this.init();
    }

    init() {
        // 创建图标按钮和聊天窗口元素
        this.createIcon();
        this.createChatWindow();

        // 初始化事件监听器
        this.iconButton.addEventListener('click', () => this.toggleChat());
        this.closeButton.addEventListener('click', () => this.toggleChat());

        // 动态调整大小
        window.addEventListener('resize', () => this.adjustSize());

        // 确保聊天窗口在初始化时不显示
        this.hideChat();
    }

    createIcon() {
        this.iconButton = document.createElement('button');
        this.iconButton.className = 'chat-icon';
        this.iconButton.innerHTML = '💬'; // 或者使用 <img> 标签
        this.container.appendChild(this.iconButton);
    }

    createChatWindow() {
        this.chatWindow = document.createElement('div');
        this.chatWindow.className = 'chat-window hidden';

        this.chatHead = document.createElement('div');
        this.chatHead.className = 'chat-head';


        this.closeButton = document.createElement('button');
        this.closeButton.className = 'close-button';
        this.closeButton.textContent = 'X';

        this.chatHead.appendChild(this.closeButton);

        this.chatContent = document.createElement('div');
        this.chatContent.className = 'chat-content';

        const messageInputContainer = document.createElement('div');
        messageInputContainer.className = 'message-input-container';

        const messageInput = document.createElement('input');
        messageInput.type = 'text';
        messageInput.placeholder = 'Type a message...';
        messageInput.id = 'message-input';

        const sendButton = document.createElement('button');
        sendButton.className = 'send-button';
        sendButton.textContent = 'Send';

        messageInputContainer.appendChild(messageInput);
        messageInputContainer.appendChild(sendButton);

        this.chatWindow.appendChild(this.chatHead);
        this.chatWindow.appendChild(this.chatContent);
        this.chatWindow.appendChild(messageInputContainer);

        this.container.appendChild(this.chatWindow);

        // 添加消息发送事件
        messageInput.addEventListener('keypress', (event) => {
            if (event.key === 'Enter') {
                this.sendMessage(event.target.value);
                event.target.value = '';
            }
        });

        sendButton.addEventListener('click', () => {
            const inputValue = messageInput.value.trim();
            if (inputValue !== '') {
                this.sendMessage(inputValue);
                messageInput.value = '';
            }
        });
    }

    toggleChat() {
        if (this.isChatVisible) {
            this.hideChat();
        } else {
            this.showChat();
        }
    }

    showChat() {
        this.iconButton.classList.add('hidden');
        this.chatWindow.classList.remove('hidden');
        this.isChatVisible = true;
        this.adjustSize();
    }

    hideChat() {
        this.iconButton.classList.remove('hidden');
        this.chatWindow.classList.add('hidden');
        this.isChatVisible = false;
        this.adjustSize();
    }

    adjustSize() {
        if (this.isChatVisible) {
            this.chatWindow.style.width = this.options.width;
            this.chatWindow.style.height = this.options.height;
            this.scrollToBottom();
        }
    }

    sendMessage(message) {
        this.displayMessage(message, 'user');
        this.answer(message);
    }

    displayMessage(message, sender) {
        const messageWrapper = document.createElement('div');
        messageWrapper.className = `message ${sender}`;

        const avatar = document.createElement('img');
        avatar.src = sender === 'user' ? '小粤1.png' : '猜你想问.png';
        avatar.alt = `${sender} avatar`;
        avatar.className = 'avatar';

        const messageElement = document.createElement('p');
        messageElement.textContent = message;
        messageElement.className = 'message-text'; // 添加类名以应用特定样式
        
        messageWrapper.appendChild(sender === 'user' ? messageElement : avatar);
        messageWrapper.appendChild(sender === 'user' ? avatar : messageElement);

        this.chatContent.appendChild(messageWrapper);
        this.scrollToBottom();
    }


    async answer(message) {
        try {
            const answer = await this.fileAnswer(message);
            this.displayMessage(`${answer}`, 'system');
        } catch (error) {
            console.error('Error:', error);
        }
    }

    scrollToBottom() {
        this.chatContent.scrollTop = this.chatContent.scrollHeight;
    }

    async fileAnswer(userMessage) {
        const url = "https://api.coze.cn/v1/workflow/stream_run";
        const headers = {
            Authorization: "Bearer pat_QT02iNX01tgs42ylsZsnLxOB4XUo3MoaaoB59mi6l4WqhiKdE7hIC5az2Y0xG1JL", // 替换为您的访问令牌
            "Content-Type": "application/json",
            Accept: "*/*",
        };
        const data = {
            workflow_id: "7440323635887947826",
            bot_id: "7440281554003509289",
            parameters: {
                BOT_USER_INPUT: userMessage
            }
        };
        try {
            const response = await fetch(url, {
                method: "POST",
                headers: headers,
                body: JSON.stringify(data),
            });
            if (!response.ok) {
                throw new Error("Network response was not ok");
            }
            const reader = response.body.getReader();
            const decoder = new TextDecoder("utf-8");
            const readStream = async () => {
                let buffer = ""; // 用于存储未处理完的chunk
                let formattedData = []; // 用于存储最终的格式化数据
                while (true) {
                    const { done, value } = await reader.read();
                    if (done) {
                        break;
                    }
                    buffer += decoder.decode(value, { stream: true });
                    const lines = buffer.split("\n");
                    lines.forEach((line) => {
                        if (line.startsWith("data:")) {
                            const jsonData = line.substring(5).trim(); // 移除 "data:" 前缀
                            try {
                                const json = JSON.parse(jsonData); // 解析 JSON 数据
                                if (json.cost === "0") {
                                    this.cozedata1 = json.content;
                                }
                            } catch (error) {
                                console.error("Error parsing JSON:", error);
                            }
                        }
                        if (line.includes("Done")) {
                            const jsonStringArray = this.cozedata1;
                            let parsedData = [];
                            if (typeof jsonStringArray === 'string') {
                                try {
                                    parsedData = JSON.parse(jsonStringArray);
                                } catch (error) {
                                    console.error("Error parsing JSON:", error);
                                    parsedData = [];
                                }
                            } else if (Array.isArray(jsonStringArray)) {
                                parsedData = jsonStringArray;
                            } else {
                                console.error("Invalid data type:", typeof jsonStringArray);
                                parsedData = [];
                            }
                            if (Array.isArray(parsedData)) {
                                try {
                                    parsedData = parsedData.map(jsonStr => JSON.parse(jsonStr));
                                } catch (error) {
                                    console.error("Error parsing JSON objects:", error);
                                    parsedData = [];
                                }
                            }
                            formattedData = parsedData.map(item => {
                                const link = item.policy_link.match(/(.*?\.html)/)?.[1] || item.policy_link;
                                return `<a href="${link}" target="_blank">${item.policy_name}</a>`;
                            });
                            console.log("Final Answer Content1111:", formattedData.join('\n'));
                        }
                    });
                }
                return formattedData;
            };
            const formattedData = await readStream();
            return formattedData;
        } catch (error) {
            console.error("Error sending request to Coze:", error);
            return [];
        }
    }
}

// 默认配置
const defaults = {
    width: '350px',
    height: '650px',
    themeColor: '#007bff'
};

// 暴露给全局对象
window.ChatSDK = function (containerSelector, options) {
    new ChatComponent(document.querySelector(containerSelector), options);
};